package cn.chinaflame.pagodas.service.api;

import cn.chinaflame.pagodas.api.YanwuPayAPI;
import cn.chinaflame.pagodas.constant.Sysconst;
import cn.chinaflame.pagodas.constant.YanwuPayParam;
import cn.chinaflame.pagodas.entity.PaOrder;
import cn.chinaflame.pagodas.enums.CodeEnum;
import cn.chinaflame.pagodas.repository.PaOrderRepository;
import cn.chinaflame.pagodas.req.PaydataReq;
import cn.chinaflame.pagodas.utils.*;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.SpringProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;

/**
 * @author wwt
 * @date 2018年1月15日 下午8:00:41
 */
@Service
public class YanwuPayService {
    private final static Logger log = LoggerFactory.getLogger(YanwuPayService.class);

    @Autowired
    private PaOrderRepository paOrderRepository;

    /**
     * @param req
     * @return
     */
    public String unifiedOrder(@RequestBody PaydataReq req, HttpServletRequest request) {
        String result = "";
        try {
            PaOrder order = paOrderRepository.findOne(req.getOrderNo());
            ParamPreconditions.checkNotNull(order, CodeEnum.FAIL.getCode(), "未找到订单信息");
            String customerIP = IPUtil.getIpAddr(request);
            req.setInputCharset(YanwuPayParam.inputCharset);
            req.setVersion(YanwuPayParam.version);
            req.setLanguage(YanwuPayParam.language);
            req.setOrderCurrency(YanwuPayParam.orderCurrency);
            req.setTradeType(YanwuPayParam.tradeType);
            req.setPayWay(YanwuPayParam.payWay);
            req.setNotifyUrl(SpringProperties.getProperty("pay.payment.notify_ty_url"));
            req.setOrderDatetime(DateTimes.nowDateTimetrim());
            req.setMerchantId(SpringProperties.getProperty("pay.payment.merchantId"));
            req.setCustomerIP(customerIP);
            //String url = SpringProperties.getProperty("pay.payment.url");
            String registKey = SpringProperties.getProperty("pay.payment.registKey");
            //判断是否在支付平台注册
            log.info("注册请求串userid:{},merchantId:{},registKey:{}", req.getUserId(), req.getMerchantId(), registKey);
            String rs = registered(req.getUserId(), req.getMerchantId(), registKey);
            log.info("注册结果rs:{}", rs);
            Map<String, String> val = Jackson.readJson(rs, new TypeRef<Map<String, String>>());
            if (!Sysconst.PAY_HAS_REGIST_CODE.equals(val.get("errorCode")))
                ParamPreconditions.checkArgument(Sysconst.PAY_SUCCESS_CODE.equals(val.get("errorCode")), CodeEnum.FAIL.getCode(), "支付用户绑定失败");
            log.info("支付请求串req:{}", req);
            result = YanwuPayAPI.commitOrder(req.getCustomerIP(), new BigDecimal(req.getOrderAmount()), req.getMerchantName(), req.getGoodsName(), req.getGoodsCount(), req.getPayType(), req.getIssuerId(), YanwuPayParam.directFlag, req.getMerchantId(), req.getReturnUrl(), req.getNotifyUrl(), "");
            JSONObject obj = JSONObject.parseObject(result);
            /**
             * pay.payment.url=http://tupay.china-flame.cn/gateway/trade/pay
             */
            //----------------------------------------------------------------------------------强哥---------------------------------------------
//		Map<String, String> receiveMap = Jackson.readJson(receive, new TypeRef<Map<String, String>>());
            log.info("下单支付结果receive:{}", result);
            if (Sysconst.PAY_SUCCESS_CODE.equals(obj.get("responseCode"))) {
                order.setPayTime(DateTimes.nowDateTime());
                order.setUpdatetime(DateTimes.nowDateTime());
                order.setPayStatus(Sysconst.PAY_STATUS_DOING);
                //order.setSerialNumber(obj.get("orderNo"));
                order = paOrderRepository.saveAndFlush(order);
				/*ScheduleTime time = new ScheduleTime(15, TimeUnit.MINUTES);
				PaOrderFailure orderFailure = new PaOrderFailure(order.getId(), Sysconst.PAY_STATUS_DOING, Sysconst.PAY_STATUS_ORDER_TIMEOUT);
				PaOrderSchedule.getInstance().startTask(orderFailure, time);*/
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @param userid
     * @param merchantId
     * @param key
     * @return
     */
    public String registered(String userid, String merchantId, String key) {
        String url = "http://tupay.china-flame.cn/gateway/user/regist ";
        String queryStr = "merchantId=" + merchantId + "&partnerUserId=" + userid + "&key=" + key;
        System.out.println(Digests.md5DigestAsHex(queryStr));
        Map<String, String> map = Maps.newHashMap();
        map.put("merchantId", merchantId);
        map.put("partnerUserId", userid);
        map.put("sign", Digests.md5DigestAsHex(queryStr).toUpperCase());
        String receive = HttpPostUtil.doPost(url, Jackson.writeJson(map));
        return receive;
    }

    /**
     * H5退款
     *
     * @param req
     * @return
     */
    public String refund(String oldorderId, String amount) {
        String result = YanwuPayAPI.merchantRefund(oldorderId, new BigDecimal(amount), "");
        return result;
    }
}
